<template>
    <div>
        <button class="btn-create" @click="open">
            修改头像
        </button>
        <AppDialogForm ref="refDialog" title="修改头像" @save="save">
            <div class="modal-body">
                <div class="addpaymethod-form add-course-info">
                    <img id="imagePreview" :src="modelValue">
                </div>
                <input type="file" id="file" class="form-control" @change="uploadImg" />
                <a class="btn btn-success">点击选择</a>
            </div>
        </AppDialogForm>

    </div>
</template>
<script setup>
import teacherApi from '@/api/teacherApi'
import masterApi from '@/api/masterApi'
import adminApi from '@/api/adminApi'
import fileApi from '@/api/fileApi'

import useUserInfo from '@/store/user'
const userInfo = useUserInfo()
const refDialog = ref(null)
const open = () => {
    refDialog.value.open()
}
// import fileApi from '@/composables/fileApi.js'
const uploadImg = e => {
    console.log(e.target.files[0])
    const file = e.target.files[0]
    if (file) {
        const reader = new FileReader();
        reader.onload = function (e) {
            imagePreview.src = e.target.result;
            imagePreview.style.display = 'inline';
        };
        reader.readAsDataURL(file);
    }
}
/**
 * 上传头像
 * 1. 调用接口，传入图片
 * 2. 调用接口，更新老师头像
 * 3. 关闭弹层
 */
const save = async () => {
    const file = document.getElementById('file').files[0]
    const data = new FormData()
    data.append('file', file)
    const res = await fileApi.uploadImg(data)
    if (userInfo.data.user.type == 'teacher')
        await teacherApi.put(userInfo.data.user.id, { avatar: res.uploadedFile.url })
    else if (userInfo.data.user.type == 'master')
        await masterApi.put(userInfo.data.user.id, { avatar: res.uploadedFile.url })
    else if (userInfo.data.user.type == 'admin')
        await adminApi.put(userInfo.data.user.id, { avatar: res.uploadedFile.url })

    emit('update:modelValue', res.uploadedFile.url)
    userInfo.data.user.avatar = res.uploadedFile.url
    refDialog.value.close()

}
// v-model

defineProps({
    modelValue: {
        type: String,
        default: ''
    }
})

const emit = defineEmits(['update:modelValue'])


</script>
